package com.est.dase;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.est.dase.adapter.ListAdapterSettings;
import com.est.dase.database.CreateDataBaseDevice;
import com.est.dase.database.DataBase;
import com.est.dase.query.GetContacts;
/**
 *
 * @author Fernando Geraldes, Jaime Santos, Jorge Silva
 *
 */
public class WhiteList extends Activity{

	private Dialog dialog;

	private DataBase db;

	private SQLiteDatabase dbEvent;

	private String[] getContact = null;

	private ListView list;

	private ListView listView;

	private SimpleAdapter adapter = null;
	private ArrayList<String> listNameSelect;
	private ArrayList<String> listNumberSelect;
	private TextView wait;

	/** Called when the activity is first created. */
	@SuppressWarnings("rawtypes")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.white_list);


		wait = (TextView) findViewById(R.id.waittext);
		wait.setText(R.string.whitelist_wait);


		TextView addWite = (TextView) findViewById(R.id.text_add);
		//addWite.setText("Add Contact to Black List");
		addWite.setText(R.string.whitelist_text);

		CreateDataBaseDevice cdb = new CreateDataBaseDevice(this); 
		db = cdb.getDataBase();
		//dbEvent = db.getWritableDatabase();
		listView = (ListView) findViewById(R.id.list_white_list);
		getList();

		dialog = new Dialog(this);		
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_contacts);
		dialog.setCancelable(false);

		Button ok = (Button) dialog.findViewById(R.id.ok_dialog);
		ok.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				dbEvent = db.getWritableDatabase();
				ContentValues values = new ContentValues();				

				for(int i=0; i<listNameSelect.size(); i++){
					values.put("NAME", listNameSelect.get(i));
					values.put("NUMBER", listNumberSelect.get(i));
					values.put("STATUS_VALUE", listNumberSelect.get(i));
					dbEvent.insertOrThrow("WHITE_LIST", null, values);
				}
				db.close();
				getList();
				dialog.dismiss();
			}
		});
		Button cancel = (Button) dialog.findViewById(R.id.cancel_dialog);
		cancel.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		final Thread thread = new Thread(){
			public void run() {
				GetContacts getContacts = new GetContacts(WhiteList.this);
				getContact = getContacts.getContact();
				List<Map<String, String>> data1 = new ArrayList<Map<String, String>>();

				for(int j =0; j<getContact.length;j++)
					data1.add(addData(getContact[j]));

				adapter = new SimpleAdapter(WhiteList.this, data1, android.R.layout.simple_list_item_multiple_choice, new String[] { "Name" }, new int[] { android.R.id.text1 });
			}
		};
		thread.start();

		FrameLayout add = (FrameLayout) findViewById(R.id.add);
		add.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				while(adapter == null){
				}

				thread.stop();
				listNameSelect = new ArrayList<String>();
				listNumberSelect = new ArrayList<String>();

				list = (ListView) dialog.findViewById(R.id.list_contacts);
				list.setAdapter(adapter);
				list.setCacheColorHint(Color.TRANSPARENT);
				list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

				list.setOnItemClickListener(new OnItemClickListener() {

					public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
							long arg3) {

						String sqlStatement = "SELECT * FROM WHITE_LIST";
						final HashMap[] hash = sqlStatement(sqlStatement);

						boolean status = true;

						if(hash.length > 0){
							for(int i=0; i<hash.length; i++){
								//System.out.println("NUMBER: " + hash[i].get("NUMBER") + "\n" + GetContacts.listNumber.get(arg2));
								if(hash[i].get("NUMBER").equals(GetContacts.listNumber.get(arg2))){
									status = false;
								}
							}
							if(status){
								listNameSelect.add(GetContacts.listName.get(arg2));
								listNumberSelect.add(GetContacts.listNumber.get(arg2));
							}
						}else{
							listNameSelect.add(GetContacts.listName.get(arg2));
							listNumberSelect.add(GetContacts.listNumber.get(arg2));
						}
					}
				});
				dialog.show();
			}
		});

		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int arg2, long arg3) {
				String sqlStatement = "SELECT * FROM WHITE_LIST";
				final HashMap[] hash = sqlStatement(sqlStatement);				

				dbEvent = db.getWritableDatabase();

				AlertDialog.Builder builder = new AlertDialog.Builder(WhiteList.this);
				builder.setMessage("Delete "+hash[arg2].get("NAME")+"\n")
				.setCancelable(false)
				.setPositiveButton("YES", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						dbEvent.delete("WHITE_LIST", "NUMBER=?", new String[]{ String.valueOf(hash[arg2].get("NUMBER"))});

						getList();
					}
				})
				.setNegativeButton("NO", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
				AlertDialog alert = builder.create();
				alert.show();

				return false;
			}
		});
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public HashMap[] sqlStatement(String sqlStatement) {
		//db.close();
		SQLiteDatabase dbEvent = db.getReadableDatabase();
		Cursor cursor = dbEvent.rawQuery(sqlStatement, null);
		HashMap[] hash = new HashMap[cursor.getCount()];

		this.startManagingCursor(cursor);
		cursor.moveToPrevious();

		for(int j=0;j<cursor.getCount();j++){
			hash[j]=new HashMap<String, String>();
			cursor.moveToNext();			
			for(int i=0;i<cursor.getColumnCount();i++){
				hash[j].put(cursor.getColumnName(i), cursor.getString(i));
			}
		}
		db.close();
		return hash;
	}

	@SuppressWarnings("rawtypes")
	public void getList(){
		String sqlStatement = "SELECT * FROM WHITE_LIST";
		final HashMap[] hash = sqlStatement(sqlStatement);

		String[] list1 = new String[hash.length];

		for(int i=0; i<hash.length; i++){
			String result = hash[i].get("NAME")+ " " + hash[i].get("NUMBER");
			list1[i]=result;
		}

		int[] num = new int[list1.length];

		listView.setCacheColorHint(Color.TRANSPARENT);
		ListAdapterSettings listAdapter = new ListAdapterSettings(this, list1,num);

		listView.setAdapter(listAdapter);
		
		if(hash.length == 0){
			//toast.show();
			wait.setVisibility(View.VISIBLE);
		}else{
			wait.setVisibility(View.INVISIBLE);
		}
	}

	private Map<String, String> addData(String name) {
		Map<String, String> mapList = new HashMap<String, String>();
		mapList.put("Name", name);
		return mapList;
	}
}
